#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
舆论监控演示工具

展示舆论监控功能的非交互式演示。
"""

import asyncio
import sys
import os

# 添加项目根目录到 Python 路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from sentiment.analyzer import SentimentAnalyzer
from sentiment.keywords import KeywordManager
from monitoring.monitor import SentimentMonitor, MonitorTarget
from monitoring.rules import MonitoringRules
from monitoring.alerts import AlertManager

async def demo_video_analysis():
    """演示视频舆情分析"""
    print("\n🎯 舆论监控系统演示")
    print("="*60)
    
    # 初始化组件
    print("📱 初始化分析组件...")
    analyzer = SentimentAnalyzer()
    monitor = SentimentMonitor()
    rules = MonitoringRules()
    alerts = AlertManager()
    
    # 模拟视频评论数据
    demo_comments = [
        "这个产品真的很好用，推荐大家试试！",
        "质量不错，物流也很快，满意",
        "服务态度很好，会继续支持的",
        "这什么垃圾产品，完全不能用",
        "太坑了，质量差得要命",
        "骗子商家，大家千万别买",
        "一般般吧，没有特别的感觉",
        "价格还可以，性价比不错",
        "用了一段时间，还算稳定",
        "客服回复很及时，点赞"
    ]
    
    print(f"📊 分析 {len(demo_comments)} 条评论舆情...")
    print("-" * 60)
    
    # 分析每条评论
    results = []
    for i, comment in enumerate(demo_comments, 1):
        result = analyzer.analyze_sentiment(comment)
        results.append(result)
        
        # 显示分析结果
        sentiment_emoji = "😊" if result["sentiment"] == "positive" else "😠" if result["sentiment"] == "negative" else "😐"
        threat_color = "🔴" if result["threat_level"] >= 4 else "🟡" if result["threat_level"] >= 2 else "🟢"
        
        print(f"{i:2d}. {sentiment_emoji} {result['sentiment'].upper():8} | 分数: {result['score']:.3f} | 威胁: {threat_color} {result['threat_level']}/5")
        print(f"    评论: {comment}")
        if result["keywords"]:
            print(f"    关键词: {', '.join(result['keywords'])}")
        print()
    
    # 统计结果
    positive_count = sum(1 for r in results if r["sentiment"] == "positive")
    negative_count = sum(1 for r in results if r["sentiment"] == "negative")
    neutral_count = len(results) - positive_count - negative_count
    avg_score = sum(r["score"] for r in results) / len(results)
    avg_threat = sum(r["threat_level"] for r in results) / len(results)
    
    print("📈 统计分析结果:")
    print("-" * 60)
    print(f"   正面评论: {positive_count:2d} 条 ({positive_count/len(results)*100:5.1f}%)")
    print(f"   负面评论: {negative_count:2d} 条 ({negative_count/len(results)*100:5.1f}%)")  
    print(f"   中性评论: {neutral_count:2d} 条 ({neutral_count/len(results)*100:5.1f}%)")
    print(f"   平均分数: {avg_score:.3f}")
    print(f"   平均威胁等级: {avg_threat:.1f}/5")
    
    # 舆情风险评估
    risk_level = "低"
    risk_color = "🟢"
    if negative_count / len(results) > 0.4 or avg_threat > 3:
        risk_level = "高"
        risk_color = "🔴"
    elif negative_count / len(results) > 0.2 or avg_threat > 2:
        risk_level = "中"
        risk_color = "🟡"
    
    print(f"   舆情风险: {risk_color} {risk_level}")
    
    # 检查监控规则
    print("\n🚨 监控规则检查:")
    print("-" * 60)
    
    # 规则1: 负面评论比例检查
    negative_ratio = negative_count / len(results)
    if negative_ratio > 0.3:
        print(f"⚠️  [高风险] 负面评论比例过高: {negative_ratio*100:.1f}%")
        print(f"   建议: 及时关注用户反馈，改进产品或服务质量")
    else:
        print(f"✅ [正常] 负面评论比例: {negative_ratio*100:.1f}% (< 30%)")
    
    # 规则2: 威胁等级检查
    high_threat_count = sum(1 for r in results if r["threat_level"] >= 4)
    if high_threat_count > 0:
        print(f"⚠️  [高风险] 发现 {high_threat_count} 条高威胁评论")
        print(f"   建议: 优先处理高威胁评论，进行危机公关")
    else:
        print(f"✅ [正常] 无高威胁等级评论")
    
    # 规则3: 关键词检查
    serious_keywords = ["垃圾", "骗子", "坑", "差得要命"]
    found_keywords = []
    for result in results:
        if result["keywords"]:
            found_keywords.extend([k for k in result["keywords"] if any(sk in k for sk in serious_keywords)])
    
    if found_keywords:
        print(f"⚠️  [中风险] 发现敏感关键词: {', '.join(set(found_keywords))}")
        print(f"   建议: 关注相关评论，及时回应用户关切")
    else:
        print(f"✅ [正常] 未发现严重负面关键词")
    
    # 生成监控建议
    print("\n💡 监控建议:")
    print("-" * 60)
    if risk_level == "高":
        print("🔴 舆情风险较高，建议:")
        print("   • 立即分析负面评论具体原因")
        print("   • 制定针对性的应对方案") 
        print("   • 加强客服响应和用户沟通")
        print("   • 考虑暂停推广活动")
    elif risk_level == "中":
        print("🟡 舆情存在一定风险，建议:")
        print("   • 密切关注评论动态变化")
        print("   • 及时回应用户关切问题")
        print("   • 优化产品或服务体验")
    else:
        print("🟢 舆情状态良好，建议:")
        print("   • 保持当前服务质量")
        print("   • 继续监控舆情变化")
        print("   • 适当推广正面口碑")
    
    print("\n🎉 舆情分析完成!")
    print("="*60)

async def demo_keyword_management():
    """演示关键词管理"""
    print("\n🏷️ 关键词管理演示")
    print("="*40)
    
    keywords = KeywordManager()
    
    negative_words = keywords.get_negative_keywords()
    positive_words = keywords.get_positive_keywords()
    monitor_words = keywords.get_monitor_keywords()
    
    print(f"📊 关键词统计:")
    print(f"   负面关键词: {len(negative_words)} 个")
    print(f"   正面关键词: {len(positive_words)} 个") 
    print(f"   监控关键词: {len(monitor_words)} 个")
    
    if negative_words:
        print(f"\n🔍 示例负面关键词:")
        sample_negative = negative_words[:10]
        for i, word in enumerate(sample_negative, 1):
            print(f"   {i}. {word}")
    
    if positive_words:
        print(f"\n😊 示例正面关键词:")
        sample_positive = positive_words[:10] 
        for i, word in enumerate(sample_positive, 1):
            print(f"   {i}. {word}")
    
    if monitor_words:
        print(f"\n🏷️ 示例监控关键词:")
        sample_monitor = monitor_words[:5]
        for i, word in enumerate(sample_monitor, 1):
            print(f"   {i}. {word}")

async def main():
    """主演示函数"""
    print("🎯 舆论监控系统 - 功能演示")
    print("="*60)
    print("本演示将展示:")
    print("• 评论情感分析")
    print("• 威胁等级评估") 
    print("• 舆情风险评估")
    print("• 监控规则检查")
    print("• 关键词管理")
    print("="*60)
    
    try:
        # 演示视频分析
        await demo_video_analysis()
        
        # 演示关键词管理
        await demo_keyword_management()
        
        print(f"\n✨ 演示完成! 要使用完整功能:")
        print(f"   • 配置Cookie: 查看 cookie-config.md")
        print(f"   • 启动Web界面: python start.py") 
        print(f"   • API文档: http://localhost:8080/docs")
        
    except Exception as e:
        print(f"❌ 演示过程出错: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(main())